#include <glib.h>

gint _int_cmp(gint a, gint b)
{
    return a - b;
}

gboolean _foreach_int_int_func (gpointer key, gpointer value, gpointer data)
{
    g_print("key:%d, value:%d user_data:%s \n", GPOINTER_TO_INT(key), GPOINTER_TO_INT(value), (gchar *)data);
    return 0;
}

gint gtree_test_int_int_data(void)
{
    GTree *tree = NULL;

    tree = g_tree_new((GCompareFunc)_int_cmp);
    if(NULL == tree) {
        g_print("g_tree_new return NULL \n");
        return 0;
    }

    g_tree_insert(tree, GINT_TO_POINTER(6), GINT_TO_POINTER(6));
    g_tree_insert(tree, GINT_TO_POINTER(8), GINT_TO_POINTER(8));
    g_tree_insert(tree, GINT_TO_POINTER(2), GINT_TO_POINTER(2));

    g_tree_foreach(tree, _foreach_int_int_func, "int-int");

    g_tree_destroy(tree);

    return 0;
}

gboolean _foreach_int_char_func (gpointer key, gpointer value, gpointer data)
{
    gchar *val = value;
    g_print("key:%c, value:%c user_data:%s \n", GPOINTER_TO_INT(key), (char)*val, (gchar *)data);
    return 0;
}

gint gtree_test_int_char_data(void)
{
    GTree *tree = NULL;
    gint i = 0;
    gchar str[3] = "abc";

    tree = g_tree_new((GCompareFunc)_int_cmp);
    if(NULL == tree) {
        g_print("g_tree_new return NULL \n");
        return 0;
    }

    for(i=0; i<3; i++) {
        g_tree_insert(tree, GINT_TO_POINTER(str[i]), &str[i]);
    }

    g_tree_foreach(tree, _foreach_int_char_func, "int-char");

    g_tree_destroy(tree);

    return 0;
}

gboolean _foreach_char_char_func (gpointer key, gpointer value, gpointer data)
{
    char *k = key;
    char *v = value;
    g_print("key:%c, value:%c user_data:%s \n", (char)*k, (char)*v, (gchar *)data);
    return 0;
}

gint gtree_test_char_char_data(void)
{
    GTree *tree = NULL;
    gint i = 0;
    gchar str[3] = "abc";

    tree = g_tree_new((GCompareFunc)strcmp);
    if(NULL == tree) {
        g_print("g_tree_new return NULL \n");
        return 0;
    }

    for(i=0; i<3; i++) {
        g_tree_insert(tree, &str[i], &str[i]);
    }

    g_tree_foreach(tree, _foreach_char_char_func, "char-char");

    g_tree_destroy(tree);

    return 0;
}

gint main(gint argc, gchar **argv)
{
    gtree_test_int_int_data();
    gtree_test_int_char_data();
    gtree_test_char_char_data();

    return 0;
}